const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

class Util {
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    /**
     * 通过mime生成文件后缀及文件名
     * @param {} mime 
     */
    getFileType(mime) {
        //获取文件后缀

        let suffix = '.jpg';
        if (mime.lastIndexOf("jpeg") != -1 || mime.lastIndexOf("jpg") != -1 ||
            mime.lastIndexOf("JPEG") != -1 || mime.lastIndexOf("JPG") != -1) {
            suffix = '.jpg';
        } else {
            suffix = '.' + mime.substr(mime.lastIndexOf("/") + 1);
        }
        return suffix;
    }
    /** 获取图片信息 */
    getImgInfo(imgSrc) {
        return new Promise((resolve, reject) => {
            wx.getImageInfo({
                src: imgSrc,
                success: (result) => {
                    resolve(result);
                },
                fail: (err) => {
                    reject(err);
                }
            })
        })

    }
    //根据dpi计算像素值
    getPixel(cm, dpi) {
        return Math.round(cm / 25.4 * dpi);
    }

    /** 创建image */
    createImage(canvas, src) {
        let count = 0;
        return new Promise((resolve, reject) => {

            wx.getImageInfo({
                src: src,
                success: function (res) {
                    const image = canvas.createImage();
                    // console.log("getimaginfo",res)
                    image.onload = function () {
                        // console.log("onload",image)
                        resolve(image);
                    }
                    image.onerror = (err) => {
                        reject(err);
                    }
                    image.src = res.path;
                }
            })
            // image.src = src;

        })
    }
    // 修改jpg图片dpi
    changeJpegDPI(base64Image, dpi) {
        var dataSplitted = base64Image.split(',');
        var format = dataSplitted[0];
        var body = dataSplitted[1];
        if (format.indexOf('image/jpeg') !== -1) {

            var headerLength = void 0;
            headerLength = 18 / 3 * 4;
            var stringHeader = body.substr(0, headerLength);
            var restOfData = body.substr(headerLength);
            var dataArray = wx.base64ToArrayBuffer(stringHeader);
            var nArray = new Uint8Array(dataArray);
            // 修改dpi
            nArray[13] = 1; // 1 pixel per inch or 2 pixel per cm
            nArray[14] = dpi >> 8; // dpiX high byte
            nArray[15] = dpi & 0xff; // dpiX low byte
            nArray[16] = dpi >> 8; // dpiY high byte
            nArray[17] = dpi & 0xff; // dpiY low byte
            var base64Header = wx.arrayBufferToBase64(dataArray);
            let finall = [base64Header, restOfData].join('');

            return finall;
        }
        return base64Image;
    }

    // base64转换
    decodeArrayBuffer(base64) {
        var bytes = (base64.length / 4) * 3;
        var ab = new ArrayBuffer(bytes);
        this.decode(base64, ab);

        return ab;
    }

    removePaddingChars(base64) {
        var lkey = this._keyStr.indexOf(base64.charAt(base64.length - 1));
        if (lkey == 64) {
            return base64.substring(0, base64.length - 1);
        }
        return base64;
    }

    decode(base64, arrayBuffer) {
        //get last chars to see if are valid
        base64 = this.removePaddingChars(base64);
        base64 = this.removePaddingChars(base64);

        var bytes = parseInt((base64.length / 4) * 3, 10);

        var uarray;
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        var j = 0;

        if (arrayBuffer)
            uarray = new Uint8Array(arrayBuffer);
        else
            uarray = new Uint8Array(bytes);

        base64 = base64.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        for (i = 0; i < bytes; i += 3) {
            //get the 3 octects in 4 ascii chars
            enc1 = this._keyStr.indexOf(base64.charAt(j++));
            enc2 = this._keyStr.indexOf(base64.charAt(j++));
            enc3 = this._keyStr.indexOf(base64.charAt(j++));
            enc4 = this._keyStr.indexOf(base64.charAt(j++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            uarray[i] = chr1;
            if (enc3 != 64) uarray[i + 1] = chr2;
            if (enc4 != 64) uarray[i + 2] = chr3;
        }

        return uarray;
    }
    /**
     * 生成唯一文件名 时间戳 + 随机数
     * @param {Number} len 生成的文件名长度
     * @param {Number} radix 指定基数
     */
    getTimeId(len, radix) {
        if (len) {
            let time = new Date().getTime();
            let uuid = getuuid(len, radix);
            return `${time}${uuid}`;
        } else {
            // console.log('请输入长度');
        }
    }

    /**
     * 生成唯一文件名
     * @param {Number} len 生成的文件名长度
     * @param {Number} radix 指定基数
     */
    getUuid(len, radix) {
        let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        let uuid = [];
        let i = 0
        radix = radix || chars.length;

        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            let r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    }

    /** 图片转base64 */
    imageTobase64(tempFilePath, type = "jpeg") {

        return new Promise((resolve,reject) => {

            wx.request({
                url: tempFilePath,
                responseType: 'arraybuffer', //最关键的参数，设置返回的数据格式为arraybuffer
                success: res => {
                    //把arraybuffer转成base64

                    let data = wx.arrayBufferToBase64(res.data);
                    resolve(('data:image/' + type + ';base64,' + data));
                },
                fail: err => {
                    // console.log("err", err)
                    reject(err);

                }
            });
        });
    }
    /**
     * 对象深度拷贝,根据目标对象键值从源对象对应的键值进行赋值
     * @param {Object} targetNode 
     * @param {Object} sourceNode 
     */
    deepCopy(targetNode, sourceNode) {
        Object.keys(targetNode).forEach((value, index) => {
            
            if (value in sourceNode && targetNode[value] instanceof Object) {
                this.deepCopy(targetNode[value], sourceNode[value]);
            } else {
                
                if (sourceNode[value] !== undefined) {
                    targetNode[value] = sourceNode[value];

                }
            }

        })
    }

    showErrorBox(content="",title="温馨提示"){
        wx.showModal({
            title: title,              // 提示的标题
            content: content,              // 提示的内容
            showCancel:false,
            confirmText: "确定",            // 确认按钮的文字，最多4个字符
            confirmColor: "#576B95",        // 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串
        })
    }
}


const Utils = new Util();
export {
    Utils,
    formatTime
};